package com.lx.fav.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lx.fav.dao.TagFavMapper;
import com.lx.fav.dao.TagMapper;
import com.lx.fav.entity.Fav;
import com.lx.fav.dao.FavMapper;
import com.lx.fav.entity.Tag;
import com.lx.fav.entity.TagFav;
import com.lx.fav.service.BizException;
import com.lx.fav.service.IFavService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lx.fav.util.MBHelp;
import com.lx.fav.util.Utils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lx
 * @since 2024-10-28
 */
@Service
public class FavServiceImpl extends ServiceImpl<FavMapper, Fav> implements IFavService {

    @Override
    public void create(Fav fav) throws BizException {
        //验证用户输入
        Utils.checkEmpty(fav.getName(), "请输入网址名称", -1);
        Utils.checkEmpty(fav.getAddr(), "请输入网址", -2);
        Utils.check(fav.getIntro().length() < 2, "网址介绍字数需大于2", -3);

        //验证数据库是否包含该连接
        Integer count = MBHelp.execute(session ->{
            FavMapper mapper = session.getMapper(FavMapper.class);
            LambdaQueryWrapper<Fav> lqw = new LambdaQueryWrapper<>();
            lqw.eq(Fav::getAddr, fav.getAddr());
            lqw.eq(Fav::getUid, fav.getUid());
            return mapper.selectCount(lqw);
        });
        Utils.check(count > 0, "该连接已经收藏了", -5);

        //保存记录: 3个表
        // 拆分分类
        List<Tag> tags = new ArrayList<>();
        if (fav.getTags().isBlank() == false) {
            String[] items = fav.getTags().split("[,;，；]+");
            for(String item : items){
                if(item.isBlank() == false){
                    Tag t = new Tag();
                    t.setName(item);
                    t.setUid(fav.getUid());
                    tags.add(t);
                }
            }
        }

        MBHelp.execute(session ->{
            FavMapper favMapper = session.getMapper(FavMapper.class);
            TagMapper tagMapper = session.getMapper(TagMapper.class);
            TagFavMapper tagFavMapper = session.getMapper(TagFavMapper.class);
            favMapper.insert(fav);
            for(Tag tag : tags){
                LambdaQueryWrapper<Tag> lqw = new LambdaQueryWrapper<>();
                lqw.eq(Tag::getUid, tag.getUid());
                lqw.eq(Tag::getName, tag.getName());
                Tag dbTag = tagMapper.selectOne(lqw);
                if(dbTag == null){
                    //没有分类
                    tagMapper.insert(tag);
                }else{
                    tag.setId(dbTag.getId());
                }
                TagFav tagFav = new TagFav();
                tagFav.setFid(fav.getId());
                tagFav.setTid(tag.getId());
                tagFavMapper.insert(tagFav);
            }
            return null;
        });
    }

    @Override
    public void getFavByID(int id) throws BizException {

    }


}
